package com.yww.algorithm.sort;

import java.util.Arrays;

/**
 * @author yww
 * @description 归并排序 从下到上
 * @since 2024/2/23 18:49
 */
public class MergeSortBottomUp {
    public static void sort(int[] arr) {
        int n = arr.length;
        int[] temp = new int[n];
        for (int width = 1; width < n; width = width << 1) {
            // [left, right] 合并的区间
            for (int left = 0; left < n; left += width * 2) {
                int right = Math.min(left + width * 2 - 1, n - 1);
                int leftEnd = Math.min(left + width - 1, n - 1);
                merge(arr, left, leftEnd, leftEnd + 1, right, temp);
            }
            System.arraycopy(temp, 0, arr, 0, temp.length);
        }
    }

    private static void merge(int[] arr, int i, int iEnd, int j, int jEnd, int[] temp) {
        int k = i;
        while (i <= iEnd && j <= jEnd) {
            if (arr[i] < arr[j]) {
                temp[k] = arr[i++];
            } else {
                temp[k] = arr[j++];
            }
            k++;
        }

        if (i <= iEnd) {
            System.arraycopy(arr, i, temp, k, iEnd - i + 1);
        }
        if (j <= jEnd) {
            System.arraycopy(arr, j, temp, k, jEnd - j + 1);
        }
    }

    public static void main(String[] args) {
        int[] a = {6, 5, 4, 3, 2, 1};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }

}
